using System;
using System.Web.Security;
using SpiderMaster.AspNet.TradingSystem.DataAccessLayer;

namespace SpiderMaster.AspNet.TradingSystem
{
    public sealed partial class TradingCenterMember
    {
        /// <summary> Logins the specified user.
        /// </summary>
        /// <param name="UserName">Name of the user.</param>
        /// <param name="Password">The password.</param>
        /// <returns></returns>
        internal static bool Login(string UserName, string Password)
        {
            if (Membership.GetUser(UserName).IsNull())
                return false;
            else ValidateMembership(TradingCenterMember.GetMember(UserName));

            return FormsAuthentication.Authenticate(UserName, Password);
        }

        private static void ValidateMembership(TradingCenterMember tcm)
        {
            MembersDataComponent.MembersRow mr = MemberManagement.DB.Get.Profile(tcm.UserName);
            if (tcm.IsNotNull() && (tcm.Profile.MemberId == MemberManagement.DefaultValues.IdNullValue))
                AutoUpdate(tcm);
            else if (!tcm.MembershipCreated)
                AutoUpdate(tcm);
            else if (mr.IsNull())
                AutoUpdate(tcm);
            else if (mr.Id != tcm.Profile.MemberId)
                AutoUpdate(tcm);
        }
        private static void AutoUpdate(TradingCenterMember m)
        {
            if (m.UserName.IsNotNullOrEmpty()) // No check is required for the MemberId!
                TradingCenterMember.ImportAspNetMember(m);
            else throw new InvalidOperationException("An attempt to Auto Update the Trading Center Member failed, The UserName was not attatched as expected!");
        }
    }
}